import React, { createContext, useEffect } from 'react';
import Events from './orders.events.json';
import { useAppDispatch } from '../../../app/hooks';
import { updateOrder } from '../domain/ordersSlice';
import { updatePosition } from '../domain/positionsSlice';
import { updateTick } from '../domain/ticksSlice';
import { updateExtremum } from '../domain/extremumsSlice';
import { 
    Order as DomainOrder,
} from '../domain/domain.model';
import {
    EventType,
    Order as ApiOrder, 
    Position as ApiPosition,
    Tick as ApiTick,
    Extremum as ApiExtremum,
} from './api.model';
import { EVENT_RECEIVED_INTERVAL } from '../../../constants';

interface DashboardDataProviderProps {
    children: JSX.Element | JSX.Element[];
}

function convertApiOrderToDomainOrders(order: ApiOrder): DomainOrder {
    return {
        id: order.id,
        type: order.type,
        side: order.side,
        _status: order.status,
        price: order.price,
        amount: order.amount,
        createdAt: order.createdAt,
        updatedAt: order.createdAt
    }
}

const Context = createContext<null>(null);

const DashboardDataProvider = ( {children}: DashboardDataProviderProps): React.ReactElement => {
    const dispatch = useAppDispatch();

    // useEffect(() => {
    //     Events.forEach((event) => {
    //         dispatch(updateOrder(convertApiOrderToDomainOrders(event.payload)));
    //     });
    // })
    const timeId = setInterval(() => {
        const nextEvent = Events.shift();
        if (nextEvent) {
         if (nextEvent.type === EventType.order) {
            dispatch(updateOrder(convertApiOrderToDomainOrders(nextEvent.payload as ApiOrder)));
         } else if (nextEvent.type === EventType.position) {
            dispatch(updatePosition(nextEvent.payload as ApiPosition));
         } if (nextEvent.type === EventType.tick) {
            dispatch(updateTick(nextEvent.payload as ApiTick));
         } if (nextEvent.type === EventType.extremum) {
            dispatch(updateExtremum(nextEvent.payload as ApiExtremum[]));
         } else {
            // throw new Error (`DashboardDataProvider: unknown type of the event: ${nextEvent.type}`);
         }
        } else {
            clearInterval(timeId);
        }
    }, EVENT_RECEIVED_INTERVAL);

    return (
        <Context.Provider value={null}>
            {children}
        </Context.Provider>
    )
}

export default DashboardDataProvider;